package com.cc.servlet;


import com.alibaba.fastjson2.JSON;
import com.cc.entity.AttendanceRecord;
import com.cc.entity.Page;
import com.cc.service.AttendanceRecordService;
import com.cc.service.impl.AttendanceRecordServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;

/**
 * @version 1.0
 * @description:TODO
 * @authorAdministrator
 * @date 2025/4/2 08:39
 */
@WebServlet("/attend")
public class AttendanceRecordServlet extends HttpServlet {
    AttendanceRecordService attendanceRecordService = new AttendanceRecordServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //允许所有来源访问
        resp.addHeader("Access-Control-Allow-Origin","*");
        //允许访问的方式
        resp.addHeader("Access-Control-Allow-Method","POST,GET");
        String method = req.getParameter("method")==null?
                "list":req.getParameter("method");
        switch (method) {
            case "check":
                Check(req, resp);
                break;
            case "getRecords":
                    GetRecords(req,resp);
                break;
            default:
        }
    }

    private void Check(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String employeeId = req.getParameter("employeeId");
        if (!attendanceRecordService.hasCheckedInToday(employeeId)) {
            attendanceRecordService.checkIn(employeeId);
        }else {
            attendanceRecordService.checkOut(employeeId);
        }
    }

    private void GetRecords(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageNum = req.getParameter("pageNum");
        Page<AttendanceRecord> page = new Page<>();
        if (pageNum != null && !pageNum.equals("0")) {
            page.setPageNum(Integer.parseInt(pageNum));
        }
        page = attendanceRecordService.getAttendanceRecordsByPage(page);
        String json = JSON.toJSONString(page, "yyyy-MM-dd HH:mm:ss");
        resp.getWriter().write(json);
    }
}
